//
//  ViewController.m
//  01-SQL的基本使用
//
//  Created by J on 16/7/31.
//  Copyright © 2016年 J. All rights reserved.
//

#import "ViewController.h"
#import "Shop.h"

#import <sqlite3.h>
@interface ViewController ()<UITableViewDataSource,UISearchBarDelegate>
@property (strong, nonatomic) IBOutlet UITextField *name;
@property (weak, nonatomic) IBOutlet UITextField *price;
@property (assign, nonatomic)  sqlite3 * db;//数据库 实例
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)  NSMutableArray *shops;

@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    //增加搜索框
    UISearchBar* searBar = [UISearchBar new];
    searBar.delegate = self;
    searBar.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 44);
    self.tableView .tableHeaderView = searBar;
    
    
    [self setupDb];
    [self setupData];

    
    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    [self.shops removeAllObjects];
    
    //oc 里面%% 代表一个%   数据库里面 %代表任意字符
    NSString* sql = [NSString stringWithFormat:@"select name, price from t_shop where name like '%%%@%%' or price like '%%%@%%' ;",searchText,searchText];
    
    //获取查询结果
    sqlite3_stmt *stmt = NULL;
    int status = sqlite3_prepare_v2(_db,sql.UTF8String,-1,&stmt,NULL);
    if(status == SQLITE_OK){//准备成功
        
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            //成功取出一条数据
            const  char* name =   (const  char*)sqlite3_column_text(stmt,0);
            const  char* price = (const  char*)sqlite3_column_text(stmt,1);
            NSLog(@"%s %s",name,price);
            
            Shop* shop = [Shop new];
            shop.name = [NSString stringWithUTF8String:name];
            shop.name = [NSString stringWithUTF8String:price];
            [self.shops addObject:shop];
            
        }
        
        [self.tableView reloadData];
    }
    
    
}

//查询数据
- (void)setupData{
    //准备
    const char *sql = "select name,price from t_shop;";
    
    //获取查询结果
    sqlite3_stmt *stmt = NULL;
   int status = sqlite3_prepare_v2(_db,sql,-1,&stmt,NULL);
    if(status == SQLITE_OK){//准备成功
        
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            //成功取出一条数据
            const  char* name =   (const  char*)sqlite3_column_text(stmt,0);
            const  char* price = (const  char*)sqlite3_column_text(stmt,1);
            NSLog(@"%s %s",name,price);
            
            Shop* shop = [Shop new];
            shop.name = [NSString stringWithUTF8String:name];
            shop.name = [NSString stringWithUTF8String:price];
            [self.shops addObject:shop];
            
        }
    }
    
    
    
}


- (NSMutableArray *)shops{
    if(!_shops){
        _shops = [NSMutableArray array];
    }
    return _shops;
}

- (void)setupDb{
    //连接数据库
    NSString* filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"shops.sqlite"];
    //如果数据库文件不存在,系统会自动创建文件初始化数据库
    //数据库对象实例
    int status = sqlite3_open(filePath.UTF8String,&_db);
    if(status == SQLITE_OK){
        NSLog(@"打开数据库成功");
        
        //    sqlite3_close();
        const char* sql = "create table if not exists t_shop (id integer primary key,name text not null ,price real);";
        char * errmsg = NULL;
        
        //创表
        sqlite3_exec(self.db, sql, nil, nil, &errmsg);
        
        
        if(errmsg){
            NSLog(@"创表失败 %s",errmsg);
            
        }else{
            
            
        }
        
        
        
    }else{
        NSLog(@"打开失败");
    }
    
    
}

- (IBAction)insert:(id)sender {
    
    NSString* sql = [NSString stringWithFormat:@"insert into t_shop(name ,price) values('%@',%f);",self.name.text,self.price.text.doubleValue];
    sqlite3_exec(_db, sql.UTF8String, NULL, NULL, NULL);
    
    //刷新表格
    Shop* shop = [Shop new];
    shop.name = self.name.text;
    shop.price = self.price.text;
    [self.shops addObject:shop];
    [self.tableView reloadData];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.shops.count;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ID"];
    }
    
    Shop* shop = self.shops[indexPath.row];
    cell.textLabel.text = shop.name;
    cell.detailTextLabel.text = shop.price;
    
    return cell;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
